package com.xpz.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.xpz.reggie.common.BaseContext;
import com.xpz.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * TODO
 * 检查用户是否已经完成登录
 *
 * @author wxc
 * @date 2023/2/22 22:51
 */
@WebFilter(filterName = "LoginCheckFilter", urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {
    //路径匹配器
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //1.获取本次请求UIA
        String requestURI = request.getRequestURI();
        log.info("拦截到请求：{}", requestURI);
        //不需要处理请求信息
        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/sendMsg",
                "/user/login"
        };
        //判断请求是否处理
        boolean check = check(urls, requestURI);
        //不需要处理
        if (check) {
            log.info("理请求：{}不需要处", requestURI);
            filterChain.doFilter(request, response);
            return;
        }
        //4-1判断状态，以登录直接放行
        if(request.getSession().getAttribute("employee")!=null){
            log.info("用户已登录，id为: {}",request.getSession().getAttribute("employee"));

            Long empId =(Long) request.getSession().getAttribute("employee");
            BaseContext.setCurrentId(empId);

            long id = Thread.currentThread().getId();
            log.info("线程id为:{}",id);

            filterChain.doFilter(request, response);
            return;
        }

        //4-2判断状态，以登录直接放行
        if(request.getSession().getAttribute("user")!=null){
            log.info("用户已登录，id为: {}",request.getSession().getAttribute("user"));

            Long userId =(Long) request.getSession().getAttribute("user");
            BaseContext.setCurrentId(userId);

           /* long userid = Thread.currentThread().getId();
            log.info("线程id为:{}",userid);*/

            filterChain.doFilter(request, response);
            return;
        }

        //若未登录，通过输出流方式向客户端响应数据
        log.info("用户未登录，id为: {}",request.getSession().getAttribute("employee"));
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
/*        log.info("拦截到请求：{}", request.getRequestURI());
        filterChain.doFilter(request, response);*/
    }

    /**
     * 判断请求是否处理
     *@param urls
     * @param requestUIA
     * @return
     */
    public boolean check(String[] urls, String requestUIA) {
        for (String url:urls){
            boolean match = PATH_MATCHER.match(url, requestUIA);
            if (match){
                return true;
            }
        }
        return false;
    }

}
